package com.xzp.blog.controller;

import com.alibaba.fastjson.JSON;
import com.xzp.blog.controller.base.BaseController;
import com.xzp.blog.entity.Image;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.xzp.blog.consts.ViewConsts.VIEW_IMAGELIST;


/**
 * 前台页面控制器 负责页面的跳转
 */
@Controller
public class FrontController extends BaseController {


    /**
     * 错误页
     */
    @GetMapping("/error")
    public String pErrorPage(HttpServletRequest request, Model model) {
        return "error";
    }

    /**
     * 前台首页
     * GET
     */
    @GetMapping("/index")
    public String pFrontIndex(HttpServletRequest request, Model model) throws Exception {
        //获取图片列表
        URL url = new URL("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=3&mkt=zh-CN");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
        StringBuffer sb = new StringBuffer();
        String temp;
        while ((temp = br.readLine())!=null){
            sb.append(temp);
        }
        String result = new String(sb);
        JSON json = (JSON) JSON.parse(result);
        String images = JSON.parseObject(result).getString("images");
        List<Image> list = JSON.parseArray(images,Image.class);



        String website = "http://www.bing.com";
        List<Image> imageList = new ArrayList<>();
        for (Image image : list) {
            String imageUrl = image.getUrl();
            String[] copyRight = image.getCopyright().split("©");
            image.setMoto_CN(copyRight[0].substring(0,copyRight[0].length()-2));
            image.setMoto_US("From 必应每日美图 (©"+copyRight[1]);
            image.setUrl(website+imageUrl);
            imageList.add(image);
        }

        addModelAtt(model,VIEW_IMAGELIST,imageList);
        return "index";
    }

    /**
     * 前台首页
     * POST
     */
    @PostMapping("/index")
    public String pFrontIndexPost(HttpServletRequest request, Model model) {
        return "index";
    }

    /**
     * 前台用户登录页
     */
    @GetMapping("/userlogin")
    public String pFrontUserLogin(HttpServletRequest request, Model model) {
        return "userlogin";
    }

    /**
     * 前台用户注册
     */
    @GetMapping("/userregister")
    public String pFrontUserRegister(HttpServletRequest request, Model model) {
        return "register";
    }

}
